<template>
  <div class="result">
    <van-list
      v-model="loading"
      :finished="finished"
      :error="error"
      finished-text="没有更多了"
      error-text="加载失败,请重试"
      @load="onLoad"
    >
      <van-cell 
      v-for="(article,index)  in list" 
      :key="index"
       :title="article.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from "@/api/search";
export default {
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      per_page: 20,
      error:false//控制展示加载失败的状态
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // 请求获取数据
      // 数据添加到数组列表中
      // loading状态关闭
      // 判断是否有数据有更新下一个数据页码无将加载状态finish状态设置结束
      try {
        const { data } = await getSearchResult({
          page: this.page, //页码
          per_page: this.per_page, //
          q: this.searchText,
        });
        // if(Math.random()>0.5){
        //   JSON.parse(`dsnajndjsa`)
        // }
        console.log(data);
        const { results } = data.data;
        this.list.push(...results);
        this.loading = false;
        if (results.length) {
          this.page++;
        } else {
          this.finished = true;
        }
      } catch (err) {
        this.error=true//展示加载失败状态
        this.loading=false//加载失败loading也要关闭
        this.$toast("获取失败");
      }
    },
  },
   
};
</script>

<style>
</style>